<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
use StarCloud\Library\Tool;
use StarCloud\Models\Doumvip\FanqieBook;
use StarCloud\Models\Doumvip\FanqieBookDetail;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\MultipartStream;
use StarCloud\Services\SmsService;

class FanQieOpen
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;
    private $appId = "457699";
    private $msToken = 'yOxsgRrdTX4CDAFDqNl2Drslv6mb4PWdOVRNS_l6RxKYycnE62m9jFsyyr8hkeKnOfApMc6FTYDNF4-MNHqLBNpa92fr4VAfgv11hFkR2koQXA9Dc_dRvcI-Fj6QgH_9p4yzVZr2JJxsYRccI8TxeOngXPDFfULr-iBDmuTE';
    public $apps = [
        110 => ["appId" => 110, 'name' => "今日头条", "content_tab" => 5,
            "category" => [
                ['name' => "网文", "genre" => "0"],
                ['name' => "出版文", "genre" => "6"],
                ['name' => "付费短故事", "genre" => "8"],
            ],
            "rank" => [
                ['id' => 1, "name" => "爆款榜", 'jingping' => 0, "baokuan" => 1],
                ['id' => 18, "name" => "精品内容库", 'jingping' => 1, "baokuan" => 0]
            ],
        ],
        111 => ["appId" => 111, 'name' => "番茄小说", "content_tab" => 2,
            "category" => [
                ['name' => "漫画", "genre" => "1"],
                ['name' => "有声书", "genre" => "4"],
                ['name' => "网文", "genre" => "0"],
                ['name' => "出版文", "genre" => "6"],
                ['name' => "付费短故事", "genre" => "8"],
            ],
            "rank" => [
                ['id' => 6, "name" => "拉新网文爆款榜", 'jingping' => 0, "baokuan" => 1],
                ['id' => 7, "name" => "拉新漫画爆款榜", 'jingping' => 0, "baokuan" => 1],
                ['id' => 8, "name" => "拉新出版物爆款榜", 'jingping' => 0, "baokuan" => 1],
                ['id' => 17, "name" => "拉新潜力榜单", 'jingping' => 0, "baokuan" => 0]
            ],
        ],

        112 => ["appId" => 112, 'name' => "番茄畅听", "content_tab" => 3,
            'category' => [
            ],
            "rank" => [
                ['id' => 14, "name" => "拉新爆款榜", 'jingping' => 0, "baokuan" => 1],
                ['id' => 15, "name" => "拉新潜力", 'jingping' => 1, "baokuan" => 0],
                ['id' => 16, "name" => "阅读榜", 'jingping' => 1, "baokuan" => 1],
            ],
        ],
        113 => ["appId" => 113, 'name' => "红果短剧", "content_tab" => 6,
            "category" => [
                ['name' => "短剧", "genre" => "203"],
            ],
            'rank' => [],
        ],
        114 => ["appId" => 114, 'name' => "抖音故事", "content_tab" => 1,
            'category' => [],
            "rank" => [
                ['id' => 1, "name" => "爆款榜", 'jingping' => 0, "baokuan" => 0],
                ['id' => 4, "name" => "拉新潜力", 'jingping' => 1, "baokuan" => 0],
                ['id' => 18, "name" => "精品内容", 'jingping' => 1, "baokuan" => 0],
            ],
        ],
        115 => ["appId" => 115, 'name' => "抖音漫画", "content_tab" => 4,
            'category' => [
                ['name' => "漫画", "genre" => "1"],
            ],
        ],
        128 => ["appId" => 128, 'name' => "悟空网文", "content_tab" => 7,
            'category' => [
                ['name' => "网文", "genre" => "0", "categoryIds" => '[{"mapping_name":"虐恋情深","mapping_id":"7330549723280965694","category_ids":[95]},{"mapping_name":"都市脑洞","mapping_id":"7220999555125346362","category_ids":[262]},{"mapping_name":"悬疑灵异","mapping_id":"7220999471293792316","category_ids":[10,100,751,539,747]},{"mapping_name":"都市生活","mapping_id":"7220999433238872125","category_ids":[2,261]},{"mapping_name":"都市修真","mapping_id":"7220999392466042938","category_ids":[124]},{"mapping_name":"都市种田","mapping_id":"7220999356676046909","category_ids":[263]},{"mapping_name":"鉴宝","mapping_id":"7220999317182480444","category_ids":[17]},{"mapping_name":"赘婿","mapping_id":"7220999279991586876","category_ids":[25]},{"mapping_name":"神医","mapping_id":"7220999241341075514","category_ids":[26]},{"mapping_name":"战神","mapping_id":"7220999198395596856","category_ids":[27]},{"mapping_name":"传统玄幻","mapping_id":"7220999152568631356","category_ids":[258]},{"mapping_name":"奇幻仙侠","mapping_id":"7220999063188013113","category_ids":[259]},{"mapping_name":"玄幻脑洞","mapping_id":"7220999024835297341","category_ids":[257]},{"mapping_name":"历史脑洞","mapping_id":"7220998987300470840","category_ids":[272]},{"mapping_name":"历史古代","mapping_id":"7220998929008033848","category_ids":[273,504]},{"mapping_name":"现言日常","mapping_id":"7220998858992517176","category_ids":[750]},{"mapping_name":"现言脑洞","mapping_id":"7220798987857559611","category_ids":[267]},{"mapping_name":"甜宠","mapping_id":"7220798883390029861","category_ids":[749,96]},{"mapping_name":"先婚后爱","mapping_id":"7220798845012148283","category_ids":[265,745,748]},{"mapping_name":"马甲","mapping_id":"7220798801005510717","category_ids":[266]},{"mapping_name":"年代","mapping_id":"7220798645711405116","category_ids":[79]},{"mapping_name":"萌宝","mapping_id":"7220798605555138617","category_ids":[28]},{"mapping_name":"古言脑洞","mapping_id":"7220798544913891389","category_ids":[253]},{"mapping_name":"宫斗宅斗","mapping_id":"7220798370829303863","category_ids":[246]},{"mapping_name":"医术","mapping_id":"7220798327703470136","category_ids":[247]},{"mapping_name":"种田","mapping_id":"7220798290399330363","category_ids":[23]},{"mapping_name":"快穿","mapping_id":"7220798237697900603","category_ids":[24]},{"mapping_name":"玄幻言情","mapping_id":"7220798193003397180","category_ids":[248]},{"mapping_name":"科幻","mapping_id":"7220798155174969402","category_ids":[8]},{"mapping_name":"游戏动漫","mapping_id":"7220798110774067259","category_ids":[746]},{"mapping_name":"双男主","mapping_id":"7220798069825077308","category_ids":[275]},{"mapping_name":"双女主","mapping_id":"7220798030553808933","category_ids":[704]},{"mapping_name":"衍生同人","mapping_id":"7220797989814534204","category_ids":[718]},{"mapping_name":"其他","mapping_id":"7220797304641421371","category_ids":[31]}]'],
            ],
        ],
        151 => ["appId" => 151, 'name' => "悟空短剧", "content_tab" => 7,
            'category' => [
                ['name' => "短剧", "genre" => "203"],
            ],
        ],
        152 => ["appId" => 152, 'name' => "番茄小说短剧", "content_tab" => 2,
            'category' => [
                ['name' => "短剧", "genre" => "203"],
            ],
        ],
        153 => ["appId" => 153, 'name' => "番茄畅听短剧", "content_tab" => 3,
            'category' => [
                ['name' => "短剧", "genre" => "203"],
            ],
        ],
    ];

    private $client = null;

    public function __construct()
    {
        $cookieJar = new CookieJar();
        $this->client = new Client([
            'cookies' => $cookieJar
        ]);
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getHeader($method = 'GET', $length = 0)
    {
        return $this->mockHeader($method, $length);
        return [
            'Content-Type' => 'application/json',
            'Cookie' => 'store-region=cn-hb; store-region-src=uid; is_staff_user=false; passport_mfa_token=Cjgx0lUex46msdyfRoougsVyNr2tpiRUck2jX8z%2Bm6tSby2xq3WSZOlWTB99iC6WRseKSFLQZR3ITBpKCjzMx0KLF0RY5Al4IokEyaQFd%2BUKsak4D0qJmik91XW6VGkxOft3lz8qW%2Fs7xZC7sPvxCvSOzdICDjvdkGEQrcTgDRj2sdFsIAIiAQP6y%2Bpu; d_ticket=22b204b5005d2ba1c8f9082ae163ff51eacc7; odin_tt=5f84e640c0b006d30cd7a7aacfe3864e96b10528f0858173584caa88d6d5fd2ab608bcaed4e09cfded5acb643bfb846aec2436f5a1fec25d28243130f02ea0e2; n_mh=Hv1EJfXw0zYqU4nePlN0-RVMnIEWX6hsRuiqz9swB1g; sid_guard=25c3cba75cc02da12f0e55073b73dd7f%7C1730688242%7C5184000%7CFri%2C+03-Jan-2025+02%3A44%3A02+GMT; uid_tt=e3864340927f67b906b75288bbdfac90; uid_tt_ss=e3864340927f67b906b75288bbdfac90; sid_tt=25c3cba75cc02da12f0e55073b73dd7f; sessionid=25c3cba75cc02da12f0e55073b73dd7f; sessionid_ss=25c3cba75cc02da12f0e55073b73dd7f; sid_ucp_v1=1.0.0-KDk3ZjE4M2JhM2I5ODA3NGNmNGRlZDYwN2ZlNzgzZTc0YmZlNGMyMzAKIAjsm9Da2c3IARDy6aC5Bhjj9xsgDDD_6uamBjgCQPEHGgJobCIgMjVjM2NiYTc1Y2MwMmRhMTJmMGU1NTA3M2I3M2RkN2Y; ssid_ucp_v1=1.0.0-KDk3ZjE4M2JhM2I5ODA3NGNmNGRlZDYwN2ZlNzgzZTc0YmZlNGMyMzAKIAjsm9Da2c3IARDy6aC5Bhjj9xsgDDD_6uamBjgCQPEHGgJobCIgMjVjM2NiYTc1Y2MwMmRhMTJmMGU1NTA3M2I3M2RkN2Y; s_v_web_id=verify_m4b4ioca_KdoYkUm6_GMd6_4goc_B6AD_G5kr9105xhRZ; passport_csrf_token=6f3914880d17122d574154bb0e473514; passport_csrf_token_default=6f3914880d17122d574154bb0e473514; ttwid=1%7CJPU46J7-EkwYCmDtmg9RXRPhLq00AjdOIIlNJ5SsBBQ%7C1734413495%7C2f6f466ef02b6d3cc89c9ecc58d108bd08de6fc39ff43cf9f110775779a60120'
        ];
    }

    public function getBookInfo($appId, $bookId)
    {

        if (!isset($this->apps[$appId])) {
            return false;
        }
        $appInfo = $this->apps[$appId];

        $body = [
            'app_id' => $this->appId,
            'content_tab' => $appInfo['content_tab'],
            'page_index' => 0,
            'book_id' => $bookId,
        ];
        if ($appId == '110') {
            $body['genre'] = 8;
        }

        try {
            $url = 'https://kol.fanqieopen.com/api/platform/content/book/list/v:version?';
            $query = $this->mockParams($this->getQueryParam($body));
            $url .= $query;

            $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

            $json = json_decode($response->getBody()->getContents(), true);
            if (isset($json['code']) && $json['code'] == 0) {
                if (empty($json['data']['book_list'])) {
                    return  false;
                }
                foreach ($json['data']['book_list'] as $bookInfo) {
                    $this->updateBookInfo($appInfo, $bookInfo, 0, 0, 0);
                }

                return true;
            }
        } catch (\Exception $e) {
            return  false;
        }
    }

    public function getBookList($appId) {
        if (!isset($this->apps[$appId])) {
            return;
        }
        $appInfo = $this->apps[$appId];

        foreach ($appInfo['rank'] as $rankItem) {
            $page_index = 1;
            while (true) {
                $body = [
                    'app_id' => $this->appId,
                    'content_tab' => $appInfo['content_tab'],
                    'rank_id' => $rankItem['id'],
                    'page_index' => $page_index,
                    'sort_key' => 7,
                ];
                try {
                    var_dump($body);
                    $url = 'https://kol.fanqieopen.com/api/platform/ranking/rank_list/v:version?';
                    $query = $this->mockParams($this->getQueryParam($body));
                    $url .= $query;

                    $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

                    $json = json_decode($response->getBody()->getContents(), true);
                    if (isset($json['code']) && $json['code'] == 0) {
                        if (empty($json['data']['rank_books'])) {
                            var_dump("更新完毕");
                            break;
                        }
                        foreach ($json['data']['rank_books'] as $bookInfo) {
                            $this->updateBookInfo($appInfo, $bookInfo, $rankItem['baokuan'], $rankItem['jingping'],$rankItem['id']);
                        }
                    } else {
                        var_dump("更新完毕");
                        break;
                    }
                }catch (\Exception $e) {
                    var_dump($e->getMessage());
                }
                $page_index++;
            }
        }

        foreach ($appInfo['category'] as $cateItem) {
            if (!isset($cateItem['categoryIds'])) {
                $body = [
                    'app_id' => $this->appId,
                    'content_tab' => $appInfo['content_tab'],
                    'genre' => $cateItem['genre'],
                    'sort_key' => 7,
                ];
                $this->queryBook($body, $appInfo);
            } else {
                $categories = json_decode($cateItem['categoryIds'], true);
                foreach ($categories as $categoryItem) {
                    $body = [
                        'app_id' => $this->appId,
                        'content_tab' => $appInfo['content_tab'],
                        'genre' => $cateItem['genre'],
                        'category' => implode(',', $categoryItem['category_ids'])
                    ];
                    $this->queryBook($body, $appInfo);
                }
            }
        }
    }

    public function queryBook($body, $appInfo)
    {
        $page_index = 1;
        while (true) {

            $body['page_index'] =  $page_index;
            $body['page_size'] = 300;
            try {
                $url = 'https://kol.fanqieopen.com/api/platform/content/book/list/v:version?';
                $query = $this->mockParams($this->getQueryParam($body));
                $url .= $query;

                $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

                $json = json_decode($response->getBody()->getContents(), true);

                if (isset($json['code']) && $json['code'] == 0) {
                    if (empty($json['data']['book_list'])) {
                        break;
                    }
                    foreach ($json['data']['book_list'] as $bookInfo) {
                        $this->updateBookInfo($appInfo, $bookInfo);
                    }

                } else {
                    var_dump("更新完毕");
                    break;
                }
            }catch (\Exception $e) {
                var_dump($e->getMessage());
            }
            $page_index++;
        }
    }

    public function updateBookInfo($appInfo, $bookInfo, $isBaokuan = 0, $isJingping = 0, $rank_id = 0)
    {
        FanqieBook::updateBook($appInfo['appId'], $appInfo['name'], $bookInfo['book_id'], ($bookInfo), $isBaokuan, $isJingping, $rank_id);
        $this->getBookInfoDetail($appInfo, $bookInfo['book_id']);
    }


    public function getBookInfo1($appId, $bookId)
    {
        $appInfo = $this->apps[$appId];
        $body = [
            'app_id' => $this->appId,
            'content_tab' => $appInfo['content_tab'],
            'page_index' => 0,
            'page_size' => 500,
            'book_id' => $bookId,
        ];
        $url = 'https://kol.fanqieopen.com/api/platform/content/chapter/list/v:version?';
        $query = $this->mockParams($this->getQueryParam($body));
        $url .= $query;
        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;

    }

    public function updateBookNoDetail($conditions, $page)
    {
        $bookIds = array_column(FanqieBook::find([
            'conditions' => 'status = 0',
        ])->toArray(), 'book_id');

        var_dump("count is" . count($bookIds));

        if (empty($bookIds)) {
            return;
        }

        if (isset($conditions['conditions']) && !empty($bookIds)) {
            $conditions['conditions'] .= ' and book_id in ' . FanqieBookDetail::implodeStringArrayToString($bookIds);
        } else {
            $conditions['conditions'] = 'book_id in ' . FanqieBookDetail::implodeStringArrayToString($bookIds);
        }

        while(true) {
            $result = FanqieBookDetail::getPaginatorArrayResult($conditions, $page, 100, 'id ASC');
            if (empty($result['data'])) {
                break;
            }
            foreach ($result['data'] as $item) {
                $detail = FanqieBookDetail::findFirstById($item['id']);
                var_dump($item['book_id']);
                $chapter = $detail->getChapter();
                if(isset($chapter[0]['detail'])) {
                    var_dump("已经更新了章节");
                    FanqieBook::updateStatusOk($item['book_id']);
                } else {
                    $book = FanqieBook::findFirstByBookId($item['book_id']);
                    if ($book) {
                        $book = $book->toArray();
                        $appIds = explode('|', $book['app_id']);
                        $appInfo = $this->apps[$appIds[0]] ?? false;
                        $this->getBookInfoDetail($appInfo, $item['book_id']);
                    }
                }
            }
            $page++;
        }
    }
    public function updateBookInfoDetail()
    {
        $list = FanqieBookDetail::find([
            'conditions' => 'status = 0',
        ])->toArray();
        foreach ($list as $item) {
            $book = FanqieBook::findFirstByBookId($item['book_id']);
            if ($book) {
                $book = $book->toArray();
                $appIds = explode('|', $book['app_id']);
                $appInfo = $this->apps[$appIds[0]] ?? false;
                $this->getBookInfoDetail($appInfo, $item['book_id']);
            }
        }
    }

    public function getBookInfoDetail($appInfo, $bookId)
    {
        if (empty($appInfo)) {
            return;
        }
       $bookDetail = FanqieBookDetail::findFirstByBookId($bookId);

       if (!empty($bookDetail) && $bookDetail->getStatus() == 1) {
           $chapter = $bookDetail->getChapter();
           if(isset($chapter[0]['detail'])) {
               FanqieBook::updateStatusOk($bookId);
               return;
           }
       }

        $body = [
            'app_id' => $this->appId,
            'content_tab' => $appInfo['content_tab'],
            'page_index' => 0,
            'page_size' => 500,
            'book_id' => $bookId,
        ];

        $url = 'https://kol.fanqieopen.com/api/platform/content/chapter/list/v:version?';
        $query = $this->mockParams($this->getQueryParam($body));
        $url .= $query;
        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            $chapter = $json['data']['chapter_list'];
            $chapter = $this->getChapterDetail($chapter, $bookId, $appInfo['appId']);
            $bookDetail = FanqieBookDetail::updateBookChapter($bookId, $chapter);
            FanqieBook::updateStatusOk($bookId);
        }
        if ($bookDetail) {
            $bookDetail->updateDetailSuccess();
        }
    }

    public function getChapterDetail($chapter, $bookId, $appId, $isAll = true)
    {
        $result = $this->getCacheChapterDetail($bookId);

        if ($result) {
            return $result;
        }

        $body = [
            'app_id' => $this->appId,
            'content_tab' => $this->apps[$appId]['content_tab'] ?? 0 ,
            'book_id' => $bookId,
        ];

        foreach ($chapter as $index => &$chapterItem) {
            if ($chapterItem['pay_info'] === false && ($isAll || $index == 0)) {
                $body['item_id'] = $chapterItem['item_id'];
                $url = 'https://kol.fanqieopen.com/api/platform/content/chapter/detail/v:version?';
                $query = $this->mockParams($this->getQueryParam($body));
                $url .= $query;
                $responseDetail = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());
                $jsonChapterDetail = json_decode($responseDetail->getBody()->getContents(), true);
                if (isset($jsonChapterDetail['code']) && $jsonChapterDetail['code'] == 0) {
                    $chapterItem['detail'] = $jsonChapterDetail['data'];

                    if (isset($chapterItem['detail']['video_download_url'])) {
                        $chapterItem['detail']['normal_download_url'] = Tool::signDownloadUrl($chapterItem['detail']['video_download_url']);
                    }
                }
            }
        }

        $this->setCacheChapterDetail($bookId, $chapter);

        return $chapter;
    }

    public function setCacheChapterDetail($bookId, $chapter)
    {
        $this->cacheClass->set($this->getBookChapterCacheKey($bookId), json_encode($chapter), 900);
    }

    public function getCacheChapterDetail($bookId)
    {
        $result = $this->cacheClass->get($this->getBookChapterCacheKey($bookId));
        if ($result) {
            return json_decode($result, true);
        }

        return false;
    }

    public function getBookChapterCacheKey($bookId)
    {
        return "2024_book_chapter_book_id:" . $bookId;
    }

    public function createPromotion($task_type, $bookId, $keyword)
    {
        $url = 'https://kol.fanqieopen.com/api/platform/promotion/plan/create/v:version?';

        $body = [
            'alias_type' => $task_type,
            'alias_name' => $keyword,
            'book_id' => $bookId,
        ];
        $contentLength = strlen(json_encode($body));
        $query = $this->mockParams($this->getQueryParam([]), $body);
        $url .= $query;

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader('POST', $contentLength));

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data']['alias_id'];
        } else {
            if ($json['message'] == '未登陆') {
                SmsService::sendCode('15629037346', SmsService::SMS_SIGN_NAME, SmsService::SMS_TEMPLATE_CODE);
            }
            throw new Exception(9999, $json['message'] . "原因：字节系列产品升级， 停止申请和回填，数据不受影响");
        }
    }

    public function mockHeader($method = 'GET', $length = 0)
    {
        $header = [
            'method' => $method,
            'authority' => 'kol.fanqieopen.com',
            'accept' =>  'application/json, text/plain, */*',
            'accept-language' =>  'zh-CN,zh;q=0.9',
            'cache-control' =>  'no-cache',
            'content-type' => 'application/json',
            'pragma' =>  'no-cache',
            "priority" => "u=1, i",
            'origin' => 'https://kol.fanqieopen.com',
            'refer' => 'https://kol.fanqieopen.com/page/content?tab_type=7&top_tab_genre=-1',
            'sec-ch-ua' =>  '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
            'sec-ch-ua-mobile'=> '?0',
            'sec-ch-ua-platform' =>  '"macOS"',
            'sec-fetch-dest' =>  'empty',
            'sec-fetch-mode' =>  'cors',
            'sec-fetch-site' =>  'same-origin',
            'user-agent' =>  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
            'cookie' => 'store-region=cn-hb; store-region-src=uid; s_v_web_id=verify_m4b4ioca_KdoYkUm6_GMd6_4goc_B6AD_G5kr9105xhRZ; passport_csrf_token=6f3914880d17122d574154bb0e473514; passport_csrf_token_default=6f3914880d17122d574154bb0e473514; d_ticket=9ea98c695f6c84223e139952f99f00aceacc7; n_mh=WvKmz_JBm3TQoX7rTauE1AlsDurQPVlHp6Z-qiSc-VI; passport_mfa_token=CjiWxTgy%2FWYd67vF5zsovZ5767k5NzCjNdgURotkJx30EkrtpbHuILUpbxAOUEM9bfNMJ02Q9Pa%2BXBpKCjwGegfp%2BLxNCm55ELDPR%2FAD6Riw2oBqzWRtj%2B15IxOa%2BzUsLrq2QDuyRModMzDD4frMtFxVW7LZeDQYDuEQ28DmDRj2sdFsIAIiAQOXANhZ; odin_tt=2c1362ec7288df27db43af73ebe008c6068d2218f3aefb4b175cce1ae0cce792d5a103a2c568497f50de622f7349205d659bbd95b9ef675fa181ea62a767df01; passport_auth_status=0e7f2e0d6cf7bd772fbe702b1a52ffa7%2C5994f4a2e413063b6a6fb03f6558fe62; passport_auth_status_ss=0e7f2e0d6cf7bd772fbe702b1a52ffa7%2C5994f4a2e413063b6a6fb03f6558fe62; sid_guard=e7f9d271efa2444ff7c4fda370fb5abe%7C1736566641%7C5184000%7CWed%2C+12-Mar-2025+03%3A37%3A21+GMT; uid_tt=f11af5e86c2b06acd410553e2009cf08; uid_tt_ss=f11af5e86c2b06acd410553e2009cf08; sid_tt=e7f9d271efa2444ff7c4fda370fb5abe; sessionid=e7f9d271efa2444ff7c4fda370fb5abe; sessionid_ss=e7f9d271efa2444ff7c4fda370fb5abe; is_staff_user=false; sid_ucp_v1=1.0.0-KDE5ZjFiY2QyNmY5ZGI1ZWFlM2RmZjJkYWNkODk4OTZkNzhhZjNkMTYKIAiT-pC9t8yqBRDxzoe8Bhjj9xsgDDCK9d2pBjgCQPEHGgJsZiIgZTdmOWQyNzFlZmEyNDQ0ZmY3YzRmZGEzNzBmYjVhYmU; ssid_ucp_v1=1.0.0-KDE5ZjFiY2QyNmY5ZGI1ZWFlM2RmZjJkYWNkODk4OTZkNzhhZjNkMTYKIAiT-pC9t8yqBRDxzoe8Bhjj9xsgDDCK9d2pBjgCQPEHGgJsZiIgZTdmOWQyNzFlZmEyNDQ0ZmY3YzRmZGEzNzBmYjVhYmU; ttwid=1%7CJPU46J7-EkwYCmDtmg9RXRPhLq00AjdOIIlNJ5SsBBQ%7C1736567072%7Cb6675c4593fefa6811abe8899b695e58fa13fe7b2698ffa4d1eeaeadf9ecd943'
        ];
        if ($length) {
            $header['content-length'] = $length;
        }

        return $header;
    }

    public function mockParams($query, &$json_data = [])
    {
        $url = "http://127.0.0.1:8787/X-Bogus";
        $body = [
            "user_agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            'query' => http_build_query($query),
            'ms_token' => $this->msToken,
            'json_data' => $json_data,
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, ['Content-Type' => "application/json"]);
        $json = json_decode($response->getBody()->getContents(), true);

        $query['msToken'] = $this->msToken;
        $query['X-Bogus'] = $json['X-Bogus'] ?? "";

        $encodedParams = array();
        foreach ($query as $key => $value) {
            $encodedParams[] = $key . '=' . $value;
        }

        $json_data = array_merge($json_data, $query);

        return implode('&', $encodedParams);
    }

    public function getQueryParam($params = [])
    {
        $params['app_id'] =  $this->appId;
        $params['aid'] =  $this->appId;
        $params['origin_app_id'] =  $this->appId;
        $params['host_app_id'] =  $this->appId;

        return $params;
    }

    public function getPromotionPosts($aliasId, $pageIndex, $pageSize = 500)
    {
        $url = "https://kol.fanqieopen.com/api/platform/promotion/post/list/v:version?";

        $query = $this->mockParams($this->getQueryParam([
            'page_index' => $pageIndex,
            'page_size' => $pageSize,
            'alias_id' => $aliasId,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());
        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data']['post_records'];
        }

        return [];
    }

    public function promotionPost($aliasId, $alias_type, $post_records)
    {
        $url = "https://kol.fanqieopen.com/api/platform/promotion/post/create/v:version?";
        $body = [
            'alias_type' => intval($alias_type),
            'alias_id' => $aliasId,
            'post_records' => $post_records,
        ];

        $contentLength = strlen(json_encode($body));
        $query = $this->mockParams($this->getQueryParam([]), $body);
        $url .= $query;

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader('POST', $contentLength));

        $content = $response->getBody()->getContents();
        $json = json_decode($content, true);

        Di::getDefault()->get('logger')->info("promotionPost" . $content);

        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        }
        return false;
    }

    public function getPromotion($task_type, $page, $size)
    {
        $url = 'https://kol.fanqieopen.com/api/platform/promotion/plan/list/v:version?';

        $query = $this->mockParams($this->getQueryParam([
            'task_type' => $task_type,
            'need_post_audit' => true,
            'page_index' => $page,
            'page_size' => $size,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());


        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data']['promotion_list'];
        }
        return [];
    }

    public function getTaskIncome($taskType, $pageIndex)
    {
        $url = 'https://kol.fanqieopen.com/api/platform/user/income/task/daily/v:version?';

        $query = $this->mockParams($this->getQueryParam([
            'task_type' => $taskType,
            'page_index' => $pageIndex,
            'page_size' => 10,
            'app_id' => $this->appId,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());


        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data'];
        }
        return [];
    }

    public function getTaskIncomeDetail($taskType, $date, $pageIndex, $object_type = 1)
    {
        $url = 'https://kol.fanqieopen.com/api/platform/user/income/task/regular/detail/v:version?';


        $query = $this->mockParams($this->getQueryParam([
            'task_type' => $taskType,
            'object_type' => $object_type,
            'income_date' => $date,
            'page_index' => $pageIndex,
            'page_size' => 10,
            'app_id' => $this->appId,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data'];
        }
        return [];
    }


    public function uploadFile($filePath)
    {
        $url = 'https://kol.fanqieopen.com/api/platform/common/upload/v:version?';
        $client = new Client();

        $header = $this->getHeader();
        $header['Content-Type'] = 'multipart/form-data';

        $response = $client->request('POST', $url, array_merge($header, [
            'multipart' => [
                [
                    'name'     => 'file',
                    'contents' => fopen($filePath, 'r'),
                ]
            ],
        ]));
        // 输出响应体
       $json = json_decode($response->getBody()->getContents(), true);

       if (isset($json['data']['uri'])) {
           return $json['data']['uri'];
       }

       return false;
    }

    public function uploadWhiteFile($uri)
    {
        $url = "https://kol.fanqieopen.com/api/platform/promotion/batch_task/create/v:version?app_id=" . $this->appId;
        $body = [
            'excel_uri' => $uri,
            'job_type' => 3,
            'app_id' => $this->appId,
        ];


        $contentLength = strlen(json_encode($body));
        $query = $this->mockParams($this->getQueryParam([]), $body);
        $url .= $query;

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader('POST', $contentLength));


        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['code']) && $result['code'] == 0) {
            return true;
        }

        return false;
    }

    public function anchorList($page)
    {
        $url = "https://kol.fanqieopen.com/api/platform/anchor/list/v:version?";

        $query = $this->mockParams($this->getQueryParam([
            "page_index" => $page,
            "page_size" => 100,
            'app_id' => $this->appId,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());

        $str = $response->getBody()->getContents();
        $utf8String = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
        $result = json_decode($utf8String, true);

        if (isset($result['data']['anchor_auth_list'])) {
            return $result['data']['anchor_auth_list'];
        } else {
            var_dump($result);
        }

        return [];
    }

    public function getInviteCodes($page)
    {
        $url = "https://kol.fanqieopen.com/api/platform/user/invite_code/info/v:version?";

        $query = $this->mockParams($this->getQueryParam([
            "invite_code" => "",
            "page_index" => $page,
            "page_size" => 100,
        ]));
        $url .= $query;

        $response = $this->httpClient->sendGetRequest($url, [], $this->mockHeader());
        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['data']['invite_codes'])) {
            return $result['data']['invite_codes'];
        } else {
            var_dump($result);
        }

        return [];
    }
}